#encoding:utf-8
from django.shortcuts import render_to_response,HttpResponseRedirect
from django.template import RequestContext
from django.contrib.auth import authenticate, login
from django.contrib.auth import hashers
from django.contrib.auth.models import User
from django.utils import timezone
from models import Publicaciones, Lugares, Tags, PubFkTag, Foros, Notificaciones
import datetime
import os
import logging


#Muestra el home de la aplicacion
def home(request):
    user=request.session.get('user')
    foros_ids = Foros.objects.filter(id_usuario=user.id).values_list('id_foro', flat=True)
    lista_ids = ','.join(str(id) for id in foros_ids)
    print "ids: "+lista_ids

    if len(lista_ids)>0:
        notifs=Notificaciones.objects.extra(where=["ID_FORO IN"+"("+lista_ids+")"])
        request.session['notif']=notifs
    else:
        request.session['notif']=[]
    request.session['options']=({'dir':"general_stats",'icon':"G"},{'dir':"config",'icon':"m"})

    return render_to_response('home.html', request.session, context_instance=RequestContext(request))

#Verifica que el usuario existe en la base de datos
def validate_user(request):

    logged=request.session.get('logged')
    username=request.session.get('username')
    message=request.session.get('message')
    firstAttempt=request.session.get('firstAttempt')

    if message is '':
        message='Por favor ingresa tu contraseña de Administrador'

    if not logged:
        if not firstAttempt:
            try:
                user=User.objects.get(username=username)
                return render_to_response('login.html',{'firstAttempt':False, 'lastuser':user, 'message':message})
            except Exception, e:
                logging.exception(e)

        users=User.objects.all()
        return render_to_response('login.html',{'users':users, 'firstAttempt':True})
    return HttpResponseRedirect('home')

#Inicia la sesion del usuario si los datos de acceso son correctos
def auth(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    user = authenticate(username=username, password=password)
    if user is not None:
        login(request, user)
        request.session["logged"]=True
        request.session['user']=user
        return HttpResponseRedirect("home")

    request.session["firstAttempt"]=False
    request.session['username']=username
    request.session['message']='Usuario y/o Contraseña incorrectos'

    return HttpResponseRedirect("/dashboard")

#cierra la sesion de usuario
def logout(request):

    #Limpia todas las variables de session
    for sesskey in request.session.keys():
        del request.session[sesskey]

    #Agrega variables de session necesarias para el proximo login
    request.session['logged']=False
    request.session['firstAttempt']=True
    request.session['message']='Por favor ingresa tu contraseña de Administrador'

    return HttpResponseRedirect("/dashboard")

#Obtiene listas de usuarios agrupadas de acuerdo a ciertos criterios
def users(request):

    try:
        del request.session['aedit']
        del request.session['fedit']
    except Exception, e:
        logging.exception(e)

    request.session['users']=User.objects.all()
    request.session['countries']=Lugares.objects.all()
    request.session['recents']=User.objects.filter(date_joined__gte=datetime.date.today()-datetime.timedelta(days=10))
    request.session['active']=User.objects.filter(is_active=1)
    request.session['inactive']=User.objects.filter(is_active=0)
    request.session['admins']=User.objects.filter(is_superuser=1)
    request.session['members']=User.objects.filter(is_superuser=0)
    request.session['options']=(
        {'dir':"user_stats",'icon':"l"},
        {'dir':"add_user",'icon':"a", 'action':"+"},
        {'dir':"edit_user",'icon':"a", 'action':"8"}
    )
    return render_to_response('home.html', request.session, context_instance=RequestContext(request))

#Obtiene los datos de un usuario para la edicion de los mismos
def get_user(request):
    uid=request.GET.get('uid')
    print uid
    request.session['uedit']=User.objects.get(id=uid)
    return HttpResponseRedirect("/dashboard/users#edit_user")

#Agrega un nuevo usuario
def add_user(request):
    username = request.POST.get('username')
    password = request.POST.get('password')
    email=request.POST.get('email')
    country= Lugares.objects.get(nombre_lugar=request.POST.get('country'))
    usuario = User.objects.create_user(username=username, origen=country.id_lugar, email=email,password=password)
    usuario.first_name=request.POST.get('firstname')
    usuario.last_name=request.POST.get('lastname')
    usuario.phone=request.POST.get('phone')

    usuario.avatar=request.FILES.get('avatar') if request.FILES.get('avatar') else 'images/avatars/avatar.png'
    usuario.is_superuser=1 if request.POST.get('admin') else 0
    usuario.is_active=1 if request.POST.get('active') else 0

    usuario.save()
    return HttpResponseRedirect("/dashboard/users#user_stats")

#Actualiza los datos de un usuario
def update_user(request):

    usuario=User.objects.get(id=request.POST.get('uid'))
    passwd=hashers.make_password(request.POST.get('password')) if request.POST.get('password') else usuario.password

    usuario.password=passwd
    usuario.first_name=request.POST.get('firstname')
    usuario.last_name=request.POST.get('lastname')
    usuario.email=request.POST.get('email')
    usuario.phone=request.POST.get('phone')
    old_avatar=usuario.avatar
    usuario.avatar=request.FILES.get('avatar') if request.FILES.get('avatar') else usuario.avatar
    usuario.is_superuser=1 if request.POST.get('admin') else 0
    usuario.is_active=1 if request.POST.get('active') else 0
    usuario.origen=Lugares.objects.get(nombre_lugar=request.POST.get('country'))

    usuario.save()
    #print os.path.abspath(os.path.dirname(old_avatar))

    print old_avatar
    if old_avatar is not usuario.avatar:
        avatar_path="static/"+old_avatar.name
        abs_path=os.path.abspath(os.path.dirname(__file__))
        try:
            os.remove(os.path.normpath(os.path.join(abs_path,avatar_path)))
        except Exception, e:
            logging.exception(e)


    delete_editing_userdata(request)
    return HttpResponseRedirect("/dashboard/users#user_stats")

#elimina los datos del usuario que se estaba editando
def delete_editing_userdata(request):
    try:
        del request.session['uedit']
        del request.session['renderquery']
    except Exception, e:
        logging.exception(e)
    return HttpResponseRedirect("/dashboard/users#user_stats")

#Obtiene listas de usuarios con base a una serie de filtros
def user_runquery(request):

    cond=request.POST.get('id_condition')

    uid=request.POST.get('uid')
    users=None
    if cond !='Igual':
        if request.POST.get('id_condition') =='Empiece':
            users=User.objects.filter(id__startswith=uid)
        elif request.POST.get('id_condition') =='Termine':
            users=User.objects.filter(id__endswith=uid)
        elif request.POST.get('id_condition') =='Mayor':
            users=User.objects.filter(id__gte=uid,first_name='Juan',username='judagox')
        elif request.POST.get('id_condition') =='Menor':
            users=User.objects.filter(id__lte=uid)
        elif request.POST.get('id_condition') =='Contenga':
            users=User.objects.filter(id__contains=uid)
    else:
        users=User.objects.filter(id=uid)

    request.session['queryset']=users
    request.session['renderquery']=True
    return HttpResponseRedirect("/dashboard/users#ustats")

#Obtiene todos los articulos, organizandolos en listas segun algunos criterios
def articles(request):

    try:
        del request.session['uedit']
        del request.session['fedit']
    except Exception, e:
        logging.exception(e)

    request.session['articles']=Publicaciones.objects.all()
    request.session['recents']=Publicaciones.objects.filter(fecha_publicacion__gte=datetime.date.today()-datetime.timedelta(days=10))
    request.session['published']=Publicaciones.objects.filter(estado_publicacion=1)
    request.session['unpublished']=Publicaciones.objects.filter(estado_publicacion=0)
    request.session['options']=(
        {'dir':"article_stats",'icon':"'"},
        {'dir':"editor",'icon':"|",'id':"addarticle", 'action':"+"},
        {'dir':"aedit",'icon':"|",'id':"upd8article", 'action':"8"}
    )
    return render_to_response('home.html', request.session, context_instance=RequestContext(request))

#Obtiene los datos de un articulo para su edicion
def get_article(request):
    aid=request.GET.get('aid')
    request.session['aedit']=Publicaciones.objects.get(id_publicacion=aid)
    return HttpResponseRedirect("/dashboard/articles#aedit")

#Elimina un articulo
def delete_article(request):
    confirm=request.GET.get('delete')
    if confirm:
        article=request.session['aedit']
        tags=PubFkTag.objects.filter(id_publicacion=article.id_publicacion)

        for tag in tags:
            id_tag=tag.id_tag
            tag.delete
            id_tag.delete()

        article.delete()
    del request.session['aedit']
    return HttpResponseRedirect("/dashboard/articles#article_stats")

#Agrega un nuevo articulo
def add_article(request):

    title=request.POST.get('title')
    article = Publicaciones.create_article(title=title)
    article.estado_publicacion=1 if request.POST.get('status') else 0
    article.fecha_publicacion=timezone.now()
    article.contenido=request.POST.get('content')

    tags=request.POST.get('tags').split(',')
    article.resumen_publicacion=request.POST.get('abstract')
    article.id_usuario=User.objects.get(id=request.POST.get('usuario'))
    article.save()

    for tag in tags:
        newtag=Tags.create_tag(tag=tag)
        newtag.save()
        PubFkTag.bind_tag(pub=article, tag=newtag)

    return HttpResponseRedirect("/dashboard/articles#article_stats")

#Actualiza la informacion de un articulo
def update_article(request):

    article=request.session.get('aedit')
    article.titulo=request.POST.get('title')
    article.estado_publicacion=1 if request.POST.get('status') else 0
    article.fecha_publicacion=timezone.now()
    article.contenido=request.POST.get('content')

    article.resumen_publicacion=request.POST.get('abstract')

    #Elimina las tags antiguas
    tags=PubFkTag.objects.filter(id_publicacion=article.id_publicacion)

    for tag in tags:
        id_tag=tag.id_tag
        tag.delete
        id_tag.delete()

    #Agrega las nuevas tags
    tags=request.POST.get('tags').split(',')

    for tag in tags:
        newtag=Tags.create_tag(tag=tag)
        newtag.save()
        PubFkTag.bind_tag(pub=article, tag=newtag)

    article.save()

    delete_article(request)
    return HttpResponseRedirect("/dashboard/articles#article_stats")

def forums(request):

    try:
        del request.session['uedit']
        del request.session['aedit']
    except Exception, e:
        logging.exception(e)

    request.session['forums']=Foros.objects.all()
    request.session['recents']=Foros.objects.filter(fecha_apertura__gte=datetime.date.today()-datetime.timedelta(days=10))
    request.session['published']=Foros.objects.filter(estado_foro=1)
    request.session['unpublished']=Foros.objects.filter(estado_foro=0)
    request.session['options']=(
        {'dir':"forum_stats",'icon':"N"},
        {'dir':"add_forum",'icon':"#", 'action':"+"},
        {'dir':"edit_forum",'icon':"#", 'action':"8"}
    )
    return render_to_response('home.html', request.session, context_instance=RequestContext(request))

#Obtiene los datos de un articulo para su edicion
def get_forum(request):
    fid=request.GET.get('fid')
    request.session['fedit']=Foros.objects.get(id_foro=fid)
    return HttpResponseRedirect("/dashboard/forums#edit_forum")

#Elimina un articulo
def delete_forum(request):
    confirm=request.GET.get('delete')
    if confirm:
        forum=request.session['fedit']
        print forum.titulo_foro
        forum.delete()
    del request.session['fedit']
    return HttpResponseRedirect("/dashboard/forums#aforum_stats")

#Agrega un nuevo articulo
def add_forum(request):

    title=request.POST.get('title')
    foro = Foros.create_foro(title=title)
    foro.estado_foro=1 if request.POST.get('status') else 0
    foro.fecha_apertura=timezone.now()

    foro.descripcion=request.POST.get('description')
    foro.id_usuario=User.objects.get(id=request.POST.get('usuario'))
    foro.save()

    return HttpResponseRedirect("/dashboard/forums#forum_stats")

#Actualiza la informacion de un articulo
def update_forum(request):

    foro=request.session.get('fedit')

    foro.titulo_foro=request.POST.get('title')
    foro.estado_foro=1 if request.POST.get('status') else 0

    if foro.estado_foro==1:
        foro.fecha_cierre=timezone.now()

    foro.fecha_apertura=timezone.now()

    foro.descripcion=request.POST.get('description')
    foro.save()

    foro.save()

    delete_forum(request)
    return HttpResponseRedirect("/dashboard/forums#forum_stats")